package com.tsing.cedap.common.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.tsing.cedap.common.annotations.SystemLog;
import com.tsing.cedap.common.config.RedisManager;
import com.tsing.cedap.common.constants.IPConstant;
import com.tsing.cedap.common.entity.LogEntity;
import com.tsing.cedap.common.mapper.LogMapper;
import com.tsing.cedap.common.service.ILogService;
import com.tsing.cedap.common.vo.UserVo;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class LogServiceImpl implements ILogService {

    @Resource
    private LogMapper logMapper;

    @Autowired
    private RedisManager redisManager;

    @Override
    public void save(String token, String ip, String browser, String method, JoinPoint joinPoint, Exception exception) {
        String userId = null;
        if (StrUtil.isNotBlank(token)) {
            UserVo userVo = JSONObject.parseObject(redisManager.getString(token), UserVo.class);
            if (ObjectUtil.isNotNull(userVo)) {
                userId = userVo.getId();
            }
        }
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        String params = null;
        try {
            params = JSONObject.toJSONString(joinPoint.getArgs()[0]);
        } catch (Exception e) {
        }
        logMapper.insert(new LogEntity()
                .setUserId(userId)
                .setIp(ip)
                .setAddress(JSONObject.parseObject(HttpUtil.get(String.format(IPConstant.IP_URL, ip))).getString("addr"))
                .setBrowser(browser)
                .setRequestTime(new Date())
                .setMethod(method)
                .setDescription(signature.getMethod().getAnnotation(SystemLog.class).description())
                .setParams(StrUtil.sub(params, 0, 200))
                .setException(ObjectUtil.isNull(exception) ? null : StrUtil.sub(JSONObject.toJSONString(
                        exception, new SimplePropertyPreFilter(Throwable.class, "code", "description", "type")), 0, 200)));
    }

}
